package com.yungam.other.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.yungam.common.bean.energy.Energy;
import com.yungam.common.bean.equip.Equipment;
import com.yungam.common.service.EnergyService;
import com.yungam.common.service.EquipmentService;
import com.yungam.other.bean.MesTbElec;
import com.yungam.other.db_service.MesTbElecService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
//@Component
public class UpdateEnergyJob {

    @Resource
    private EnergyService energyService;
    @Resource
    private EquipmentService equipmentService;
    @Resource
    private MesTbElecService mesTbElecService;

    @Scheduled(fixedRate = 1000 * 60 * 30)
    public void updateEnergy() {
        log.info("现在开始给mes同步能量值");
        List<Equipment> equipmentList = equipmentService.list(new QueryWrapper<Equipment>()
                .select(Equipment.class, col -> !col.getProperty().equals("equImg")));
        Map<Integer, Double> map = Maps.newHashMap();

        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String str = now.format(df);
        String start = str + " 00:00:00", end = str + " 23:59:59";
        List<Energy> list = energyService.list(new QueryWrapper<Energy>().between("day", start, end));

        for (Energy energy : list) map.put(energy.getEquId(), energy.getNewValue());
        List<MesTbElec> tbElecs = Lists.newArrayList();
        for (Equipment equip : equipmentList) {
            MesTbElec entity = new MesTbElec();
            entity.setEquipmentNo(equip.getEquNumber())
                    .setElecQty(map.getOrDefault(equip.getEquId(), 0d))
                    .setInsertTime(new Date());
            tbElecs.add(entity);
        }
        log.info("要同步的能量列表为{}", new Gson().toJson(tbElecs));
        if (tbElecs.size() > 0) {
            mesTbElecService.saveBatch(tbElecs);
        }
        log.info("同步成功");
    }



}
